//首页登录注册区域
var login_str = '';
var logout_str = '';
login_str += "<li><a href='/login_register.html?Continue="+encodeURI(location.href)+"' >用户登录</a></li>";
login_str += "<li><a href='/login_register.html?Continue="+encodeURI(location.href)+"' >新用户注册</a></li>";
// login_str += '<li><a href=\"/passport.php\"
// target=\"_blank\">支付宝用户登录</a></li>';
login_str += '<li><a href="/help.html" target="_blank">新手帮助</a></li>';

var USER_CENTER_URL = 'http://passport.masamaso.com';		//用户中心对应的URL地址
						
jQuery(document).ready(function(){
	//将原来的用户登录/注册功能导向新增加的用户中心独立项目
	var docDomain = document.domain;

	//按照不同域名导向不同的用户中心URL
	if(docDomain.match('dev.com')){
		USER_CENTER_URL = 'http://passport.masa.dev.com';
	} else if (docDomain.match('test.')){
		USER_CENTER_URL = 'http://passporttest.masamaso.com';
	} else if (docDomain.match('www2.')){
		USER_CENTER_URL = 'http://passport2.masamaso.com';
	} else if (docDomain.match('pre.')){
		USER_CENTER_URL = 'http://passportpre.masamaso.com';
	}	
	
	
    if (getCookie('mm_customer'))
    {
    	showStateHtml();
    }
    else
    {
    	showLoginHtml();
    }
	
    bodyclick = document.getElementsByTagName('body').item(0);
    // rSelects();
    bodyclick.onclick = function(){
        for (i=0;i<selects.length;i++){
            if ((i>0) || (location.href.indexOf('flow') >= 0)) continue;
            if(jQuerym('select_info_' + selects[i].name)) jQuerym('select_info_' + selects[i].name).className = 'tag_select';
            if(jQuerym('options_' + selects[i].name)) jQuerym('options_' + selects[i].name).style.display = 'none';
        }
    }
    /** 购物车js* */
    if (document.getElementById('flowNum'))
    {
        jQuery.ajax({
            type:"POST",
            url:"/shopping.php?c=cart&a=cart_num",
            cache:false,
            dataType:'json',     // 接受数据格式
            success:function (msg){
                if (msg.num != 0) {
                    // jQuery("#flowPrice").html("总金额：￥"+parseInt(msg.price));
                    jQuery("#flowNum").html(msg.num);
                }
            }
        });
    }
    if (document.getElementById('act_li_num')) {
        if (document.getElementById('act_li_num').value > 0) jQuery("#scrollDiv").Scroll({
            line:1,
            speed:500,
            timer:2000,
            up:"btn1",
            down:"btn2"
        });
    }
});


/***  用户中心独立项目增加/修改功能，Begin **********/

//如果用户已经登录，显示用户中心的链接：用户中心、用户退出
function showStateHtml()
{
	if (document.getElementById('index_login'))
    {
		//现在应该改为统一的，不管是哪种方式登录，在Cookie中都记录的有 用户ID、用户邮箱、用户名称
		var html = '';
		var customerName = getCookie('mm_customer_name');
		if (customerName == '' || customerName == null)
		{
			var email = getCookie('mm_customer');
			if (email.indexOf('@') > 0) 
			{
				customerName = email.substring(0, email.indexOf('@'));
			}
			else
			{
				customerName = email;
			}
		}
		customerName = decodeURIComponent(escape(customerName));		
		
		
		
		html += '<li>' + customerName + '</li>';
		html += '<li><a href="/user.php">我的账户</a></li>';
		html += '<li><a href="/user_order.php">我的订单</a></li>';
		html += '<li id="my_msg"><a href="' + USER_CENTER_URL + '/web/member/user_msg.php">我的消息<span id="total_msg"></span></a></li>';
		html += '<li><a href="/help.html" target="_blank">新手帮助</a></li>';
		html += "<li><a href=\"javascript:userLogout();\" onclick=\";\">退出</a></li>";
		
		document.getElementById('index_login').innerHTML = html;
		showTotalMsg();
    }
}
//显示用户未删除的消息的条数
function showTotalMsg()
{
     if (document.getElementById('my_msg'))
    {	 	
	jQuery(function(){
	    	jQuery.getJSON(USER_CENTER_URL + "/web/member/user_msg_total.php?callback=?", function(msg) {	    
		document.getElementById('total_msg').innerHTML = "(" + msg.totalMsg +")";  
	    });
		    
	});

	
     }

}

//如果用户未登录，显示的是用户登录的链接：用户登录、用户注册、用户帮助
function showLoginHtml()
{
	 if (document.getElementById('index_login'))
     {		 
		 var locationUrl = encodeURIComponent(document.location.href);
		 
		 //var dispalyHtml = "<li><a href=\"javascript:;\"  onclick=\"ajaxLoginOrRegist('login','index.shtml');\">用户登录</a></li>";
		 //dispalyHtml += "<li><a href=\"javascript:;\"  onclick=\"ajaxLoginOrRegist('reg','/');\">新用户注册</a></li>";
		 
		 var dispalyHtml = "<li><a href=\"" + USER_CENTER_URL + "/web/register/login.php?return_url=" + locationUrl + "\">用户登录</a></li>";
	     dispalyHtml += "<li><a href=\"" + USER_CENTER_URL + "/web/register/login.php?return_url=" + locationUrl + "\">新用户注册</a></li>";
	     dispalyHtml += '<li><a href="http://www.masamaso.com/help.html" target="_blank">新手帮助</a></li>';
     	       	
         document.getElementById('index_login').innerHTML = dispalyHtml;
     }
}


//当点击用户登录、用户注册时，弹出窗口显示
/*
function ajaxLoginOrRegist(actionType, returnUrl, callBack)
{	
	jQuery('#question').html('<div style="padding:50px;border:1px solid #E7E7E7;background:#FDFDFD;text-align:center;line-height:20px;"><p><img src="http://image.masamaso.com/loading.gif" onclick="jQuery.unblockUI();" alt="loading" /></p><p>数据加载中…… <a href="javascript:;" onclick="jQuery.unblockUI();">关闭</a></p></div>');
	
	jQuery.blockUI({
		message: jQuery('#question'), 
		css: {
			top:  (jQuery(window).height()-350) /2 + 'px',
			left: (jQuery(window).width()-420)/2 + 'px',
			cursor: 'text'
		}
	});
	
	url = USER_CENTER_URL + "/web/register/user_validate_api.php?type=" + actionType 
		+ "&act=flow_login_reg&return_url=" + encodeURIComponent(returnUrl);
	
	jQuery.getJSON(url+"&jsonp_callback=?", function(data) {
		if (data.content == '' || data.content == undefined)
		{
			jQuery.unblockUI();
			if (data.url != '' && data.url != undefined) 
			{
				location.href = data.url;
			}
		}
		else
		{			
			if (typeof(data.error) == 'undefined' && window.GridsumWebDissector) {
				var _gsTracker = GridsumWebDissector.getTracker("GWD-000409");
				_gsTracker.track("/targetpage/regSuccess.html");
			}
			
			jQuery("#question").html(data.content);
		}
	});
	
}
*/



//用户退出登录
function userLogout(){
	//先删除本地的Cookie然后再进行Cookie同步
    var mm_id = getCookie('mm_customer_id');
    setCookie('mm_id',mm_id);
    delCookie('mm_customer');
    delCookie('mm_customer_name');
    delCookie('mm_customer_id');
    delCookie('mm_password');
    delCookie('mm_key');
	
	sso.default_url = '/';
	sso.logout(1);
}

/*
 * 从新修正登陆退出 ruijilai@masamaso.com 2011-3-14
 */
function index_logout(){
	//采用新的用户中心功能，原来的用户登录/注册功能先取消掉
	userLogout();
}


function index_login()
{
	//采用新的用户中心功能，原来的用户登录/注册功能先取消掉
	showStateHtml();
}


/***  用户中心独立项目增加/修改功能，End **********/








//
// 添加回车后登陆or注册
// ruijilai@masamaso.com
// 2011-2-23
function bindEvent(obj)
{
    obj.onkeypress=function(e)
    {
        if((arguments[0] || window.event).keyCode==13)
        {
            if(obj.id=='customer'  || obj.id=='password1')
                header_login();
            if(obj.id=='customer2' || obj.id=='first_password'  || obj.id=='second_password')
                register();
        }

    }
}




// 二级商品弹出层
function showFastFlow(product_id,page)
{
    jQuery('#question').html('<div style="padding:50px;border:1px solid #E7E7E7;background:#FDFDFD;text-align:center;line-height:20px;"><p><img src="http://image.masamaso.com/loading.gif" onclick="jQuery.unblockUI();" alt="loading" /></p><p>数据加载中…… <a href="javascript:;" onclick="jQuery.unblockUI();">关闭</a></p></div>');
    var isShowOverlay = true;
    if (page)
    {
        isShowOverlay = false;
    }
    jQuery.blockUI({
        message: jQuery('#question'), 
        css: {
            top:  (jQuery(window).height()-450) /2 + 'px',
            left: (jQuery(window).width()-580) /2 + 'px',
            cursor: 'text'
        },
        showOverlay:isShowOverlay
    });
    // return false;
    jQuery.ajax({
        type:"GET",
        url:"/fast_show_goods.php?"+"id="+product_id+"&act=fastview&page="+page+'&r='+Math.random(),
        cache:false,
        datatype:'html',
        success:function (msg){
            jQuery('#question').html(msg);
        },
        error: function()
        {

        }
    });
}







/* 菜单滑动 */
var cssdropdown={
    disappeardelay: 250, // set delay in miliseconds before menu disappears
    // onmouseout
    dropdownindicator: '', // specify full HTML to add to end of each menu item
    // with a drop down menu
    enablereveal: [true, 5], // enable swipe effect? [true/false, steps
    // (Number of animation steps. Integer between
    // 1-20. Smaller=faster)]
    enableiframeshim: 1, // enable "iframe shim" in IE5.5 to IE7? (1=yes,
    // 0=no)
    // No need to edit beyond here////////////////////////
    dropmenuobj: null, 
    asscmenuitem: null, 
    domsupport: document.all || document.getElementById, 
    standardbody: null, 
    iframeshimadded: false, 
    revealtimers: {},
    getposOffset:function(what, offsettype){
        var totaloffset=(offsettype=="left")? what.offsetLeft : what.offsetTop;
        var parentEl=what.offsetParent;
        while (parentEl!=null){
            totaloffset=(offsettype=="left")? totaloffset+parentEl.offsetLeft : totaloffset+parentEl.offsetTop;
            parentEl=parentEl.offsetParent;
        }
        return totaloffset;
    },
    css:function(el, targetclass, action){
        var needle=new RegExp("(^|\\s+)"+targetclass+"(jQuery|\\s+)", "ig")
        if (action=="check")
            return needle.test(el.className)
        else if (action=="remove")
            el.className=el.className.replace(needle, "")
        else if (action=="add" && !needle.test(el.className))
            el.className+=" "+targetclass
    },
    showmenu:function(dropmenu, e){
        if (this.enablereveal[0]){
            if (!dropmenu._trueheight || dropmenu._trueheight<12)
                dropmenu._trueheight=dropmenu.offsetHeight
            clearTimeout(this.revealtimers[dropmenu.id])
            dropmenu.style.height=dropmenu._curheight=0
            dropmenu.style.overflow="hidden"
            // dropmenu.style.visibility="visible";
            dropmenu.style.display="block";
            this.revealtimers[dropmenu.id]=setInterval(function(){
                cssdropdown.revealmenu(dropmenu)
            }, 10)
        }
        else{
            dropmenu.style.display="block"
        }
        var d_num = parseInt(dropmenu.id.substring(8,10));
        if (d_num != undefined) {
            d_num += 1;
        }
        else d_num = 0;
        if (document.getElementById('menu_m'+d_num)) document.getElementById('menu_m'+d_num).className = 'm'+d_num;
        // if (d_num < 9) document.getElementById('img'+dropmenu.id).src =
        // 'http://image.masamaso.com/menu_h_0'+(d_num+1)+'.gif';
        // else document.getElementById('img'+dropmenu.id).src =
        // 'http://image.masamaso.com/menu_h_'+(d_num+1)+'.gif';
        this.css(this.asscmenuitem, "selected", "add")
    },
    revealmenu:function(dropmenu, dir){
        var curH=dropmenu._curheight, maxH=dropmenu._trueheight, steps=this.enablereveal[1]
        if (curH<maxH){
            var newH=Math.min(curH, maxH)
            dropmenu.style.height=newH+"px"
            dropmenu._curheight= newH + Math.round((maxH-newH)/steps) + 1
        }
        else{ // if done revealing menu
            dropmenu.style.height="auto"
            dropmenu.style.overflow="hidden"
            clearInterval(this.revealtimers[dropmenu.id])
        }
    },
    clearbrowseredge:function(obj, whichedge){
        var edgeoffset=0
        if (whichedge=="rightedge"){
            var windowedge=document.all && !window.opera? this.standardbody.scrollLeft+this.standardbody.clientWidth-15 : window.pageXOffset+window.innerWidth-15
            var dropmenuW=this.dropmenuobj.offsetWidth
            if (windowedge-this.dropmenuobj.x < dropmenuW)  // move menu to the
                // left?
                edgeoffset=dropmenuW-obj.offsetWidth
        }
        else{
            var topedge=document.all && !window.opera? this.standardbody.scrollTop : window.pageYOffset
            var windowedge=document.all && !window.opera? this.standardbody.scrollTop+this.standardbody.clientHeight-15 : window.pageYOffset+window.innerHeight-18
            var dropmenuH=this.dropmenuobj._trueheight
            if (windowedge-this.dropmenuobj.y < dropmenuH){ // move up?
                edgeoffset=dropmenuH+obj.offsetHeight
                if ((this.dropmenuobj.y-topedge)<dropmenuH) // up no good
                    // either?
                    edgeoffset=this.dropmenuobj.y+obj.offsetHeight-topedge
            }
        }
        return edgeoffset
    },
    dropit:function(obj, e, dropmenuID){
        if (this.dropmenuobj!=null) // hide previous menu
            this.hidemenu() // hide menu
        this.clearhidemenu()
        this.dropmenuobj=document.getElementById(dropmenuID) // reference
        // drop down
        // menu
        this.asscmenuitem=obj // reference associated menu item
        this.showmenu(this.dropmenuobj, e)
        this.dropmenuobj.x=this.getposOffset(obj, "left")
        this.dropmenuobj.y=this.getposOffset(obj, "top")
        this.dropmenuobj.style.left=this.dropmenuobj.x-this.clearbrowseredge(obj, "rightedge")+"px"
        this.dropmenuobj.style.top=this.dropmenuobj.y-this.clearbrowseredge(obj, "bottomedge")+obj.offsetHeight+1+"px"
        this.positionshim() // call iframe shim function
    },
    positionshim:function(){ // display iframe shim function
        if (this.iframeshimadded){
            if (this.dropmenuobj.style.display=="block"){
                this.shimobject.style.width=this.dropmenuobj.offsetWidth+"px"
                this.shimobject.style.height=this.dropmenuobj._trueheight+"px"
                this.shimobject.style.left=parseInt(this.dropmenuobj.style.left)+"px"
                this.shimobject.style.top=parseInt(this.dropmenuobj.style.top)+"px"
                this.shimobject.style.display="block"
            }
        }
    },
    hideshim:function(){
        if (this.iframeshimadded)
            this.shimobject.style.display='none'
    },
    isContained:function(m, e){
        var e=window.event || e
        var c=e.relatedTarget || ((e.type=="mouseover")? e.fromElement : e.toElement)
        while (c && c!=m)try {
            c=c.parentNode
        } catch(e){
            c=m
        }
        if (c==m)
            return true
        else
            return false
    },
    dynamichide:function(m, e){
        if (!this.isContained(m, e)){
            this.delayhidemenu()
        }
    },

    delayhidemenu:function(){
        this.delayhide=setTimeout("cssdropdown.hidemenu()", this.disappeardelay) // hide
    // menu
    },
    hidemenu:function(){
        for (var n=0;n<14;n++) {
            // if (n < 9) document.getElementById('imgdropmenu'+n).src =
            // 'http://image.masamaso.com/menu_on_0'+(n+1)+'.gif';
            // else document.getElementById('imgdropmenu'+n).src =
            // 'http://image.masamaso.com/menu_on_'+(n+1)+'.gif';
            if (document.getElementById('menu_m'+n)) document.getElementById('menu_m'+n).className = '';
        }
        this.css(this.asscmenuitem, "selected", "remove")
        this.dropmenuobj.style.display='none'
        this.dropmenuobj.style.left=this.dropmenuobj.style.top="-1000px"
        this.hideshim()
        gl_set();
    },
    clearhidemenu:function(){
        if (this.delayhide!="undefined")
            clearTimeout(this.delayhide)
    },
    addEvent:function(target, functionref, tasktype){
        if (target.addEventListener)
            target.addEventListener(tasktype, functionref, false);
        else if (target.attachEvent)
            target.attachEvent('on'+tasktype, function(){
                return functionref.call(target, window.event)
            });
    },
    startchrome:function(){

        if (!this.domsupport)
            return
        this.standardbody=(document.compatMode=="CSS1Compat")? document.documentElement : document.body
        for (var ids=0; ids<arguments.length; ids++){
            var menuitems=document.getElementById(arguments[ids]).getElementsByTagName("a")
            for (var i=0; i<menuitems.length; i++){
                if (menuitems[i].getAttribute("rel")){
                    var relvalue=menuitems[i].getAttribute("rel")
                    var asscdropdownmenu=document.getElementById(relvalue)
                    this.addEvent(asscdropdownmenu, function(){
                        cssdropdown.clearhidemenu()
                    }, "mouseover")
                    this.addEvent(asscdropdownmenu, function(e){
                        cssdropdown.dynamichide(this, e)
                    }, "mouseout")
                    // this.addEvent(asscdropdownmenu,
                    // function(){cssdropdown.delayhidemenu()}, "click")
                    try{
                        menuitems[i].innerHTML=menuitems[i].innerHTML+" "+this.dropdownindicator
                    }catch(e){}
                    this.addEvent(menuitems[i], function(e){ // show drop
                        // down menu
                        // when main
                        // menu items
                        // are mouse
                        // over-ed
                        if (!cssdropdown.isContained(this, e)){
                            var evtobj=window.event || e
                            cssdropdown.dropit(this, evtobj, this.getAttribute("rel"))
                        }
                    }, "mouseover")
                    this.addEvent(menuitems[i], function(e){
                        cssdropdown.dynamichide(this, e)
                    }, "mouseout") // hide drop down menu when main menu items
                // are mouse out
                // this.addEvent(menuitems[i],
                // function(){cssdropdown.delayhidemenu()}, "click") //hide drop
                // down menu when main menu items are clicked on
                }
            } // end inner for
        } // end outer for
        if (this.enableiframeshim && document.all && !window.XDomainRequest && !this.iframeshimadded){ // enable
            // iframe
            // shim
            // in
            // IE5.5
            // thru
            // IE7?
            document.write('<IFRAME id="iframeshim" src="about:blank" frameBorder="0" scrolling="no" style="left:0; top:0; position:absolute; display:none;z-index:90; background: transparent;"></IFRAME>')
            this.shimobject=document.getElementById("iframeshim") // reference
            // iframe
            // object
            this.shimobject.style.filter='progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)'
            this.iframeshimadded=true
        }
    } // end startchrome
}



function jump_url(url) {
    var previous = 'index.php';
    var previous_param = '';
    var current_arr = url.split('?');
    var current_param = current_arr[1];
    var current = current_arr[0].split('.com/');
    current = current[1];
    document.getElementById('delIframe').src = 'http://www.masamaso.com/union/operate/visitor_path.php?previous='+escape(previous)+'&previous_param='+escape(previous_param)+'&current='+escape(current)+'&current_param='+escape(current_param)+'&domain='+domain;
    window.open(url);
}

function validate_customer()
{
    var customer = document.getElementById('customer').value;
    var password = document.getElementById('password').value;
    password = password.toString();
    if (!Utils.isEmail(customer))
    {
        alert('请填写您的用户名（邮箱）与密码！');
        document.getElementById('customer').focus();
        return false;
    }
    if (password.length < 6)
    {
        alert('密码不能小1于6位，请重新填写！');
        document.getElementById('password').focus();
        return false;
    }
    // if (password > 20)
    // {
    // alert('密码不能大于20位，请重新填写！');
    // document.getElementById('password').focus();
    // return false;
    // }
    var before_page = jQuery("#loading").html();
    jQuery("#loading").html("登陆中，请稍等……<a href='javascript:;' onclick='validate_customer();'>重试</a>");
    jQuery.ajax({
        type:"GET",
        url:"/user_validate.php",
        cache:false,
        dataType:'json',     // 接受数据格式
        data:"customer="+customer+"&password="+password+"&act=login",
        success:function (result){
            if (result.error == 1)
            {
                alert(result.message);
                // before_page += '<div
                // style="color:red;">'+result.message+'</div>';
                jQuery("#loading").html(before_page);
            }
            else
            {
                jQuery("#login_area").html(result.page);
            }
        }
    });
}
// 退出登陆
function logout()
{
    var mm_id = getCookie('mm_customer_id');
    setCookie('mm_id',mm_id);
    delCookie('mm_customer');
    delCookie('mm_customer_id');
    delCookie('mm_password');
    delCookie('mm_key');
    var before_page = jQuery("#loading").html();
    jQuery("#loading").html("登出中，请稍等……");
    jQuery.ajax({
        type:"GET",
        url:"/user_validate.php?act=logout",
        cache:false,
        dataType:'html',     // 接受数据格式
        success:function (result){
            if (result)
            {
                jQuery("#login_area").html(result);
            }
            else
            {
                jQuery("#loading").html(before_page);
            }
        }
    });
}

// 按下回车搜索
var keyUpdo = function(e)
{
    if(e.keyCode==13)
    {
        validate_customer();
    }
}
// 最近浏览的商品
function insert_history()
{
    var pn_dispaly = getCookie('PN').split('||');
    var bc_dispaly = getCookie('BC').split('||');
    var sn_dispaly = getCookie('SN').split('||');
    var sp_dispaly = getCookie('SP').split('||');
    var pt_dispaly = getCookie('PT').split('||');

    jQuery("#history_area").html('');
    // var hisgory = getCookie('history');
    // hisgory = eval('(' + hisgory + ')');
    var history_str = '';
    // for (key in hisgory)
    // {
    // if (hisgory[key])
    // {
    // arr = hisgory[key].split('|');
    // history_str += '<li>';
    // history_str += '<div class="goods_skim_tp"><a
    // href="goods.php?id='+arr[0]+'" title="'+arr[2]+'" target="_blank"><img
    // src="http://www.masamaso.com/upload/'+arr[3]+'_s_1.jpg" alt="'+arr[2]+'"
    // /></a></div>';
    // history_str += '<div class="goods_skim_txt gray9">';
    // history_str += '<p><a href="goods.php?id='+arr[0]+'">'+arr[2]+'</a></p>';
    // history_str += '<p class="goods_skim_price">￥'+arr[1]+'</p>';
    // history_str += '</div>';
    // history_str += '</li>';
    // jQuery("#history_area").html(history_str);
    // }
    // }

    for (var i=0;i<pn_dispaly.length;i++) {
        if (pn_dispaly[i] != '') {
            var sntext = sn_dispaly[i].slice(0,16)+"...";
            if (i == pn_dispaly.length-1)
            {
                history_str += '<li class="border_none">';
            }
            else
            {
                history_str += '<li>';
            }
            var price_type = '';
            if(pt_dispaly[i]){
                price_type = '<font style="color:#c00">'+pt_dispaly[i]+'价</font>'
            }
            history_str += '<div class="goods_skim_tp"><a href="/goods_'+pn_dispaly[i]+'.html" title="'+sn_dispaly[i]+'" target="_blank"><img src="http://image03.masamaso.com/s/'+bc_dispaly[i]+'_s_0.jpg" alt="'+sn_dispaly[i]+'" /></a></div>';
            history_str += '<div class="goods_skim_txt gray">';
            history_str += '<p><a href="/goods_'+pn_dispaly[i]+'.html" target="_blank">'+sntext+'</a></p>';
            history_str += '<p class="goods_skim_price">'+price_type+'￥'+sp_dispaly[i]+'</p>';
            history_str += '</div>';
            history_str += '</li>';
        }
    }
    jQuery("#history_area").html(history_str);
}


function login()
{
    var customer = document.getElementById('customer').value;
    var password = document.getElementById('password').value;
    password = password.toString();
    if (!Utils.isEmail(customer))
    {
        jQuery("#customer_msg").html('请填写正确的Email！');
        document.getElementById('customer').focus();
        return false;
    }
    if (password.length < 6)
    {
        jQuery("#password_msg").html('密码不能小于6位！');
        document.getElementById('password').focus();
        return false;
    }

    var before_page = jQuery("#loading").html();
    jQuery("#loading").html("登陆中，请稍等……<a href='login();'>重试</a>");
    jQuery.ajax({
        type:"POST",
        url:"/user_validate.php",
        cache:false,
        dataType:'json',     // 接受数据格式
        data:"customer="+customer+"&password="+password+"&act=login&return_url=shopping.php",
        success:function (result){
            if (result.error == 1)
            {
                jQuery("#login_msg").html(result.message);
                jQuery("#loading").html(before_page);
            }
            else
            {
                var Continue =  getArgs().Continue;
                if(Continue.length > 2){
                    sso.default_url = Continue;
                }else if (result.return_url != '')
                {
                    sso.default_url = result.return_url;
                }
                else
                {
                    sso.default_url = 'index.php';
                }
                sso.login(1);
            }
        }
    });
}
// function insert_history()
// {
// jQuery("#history_area").html('');
// var hisgory = getCookie('history');
// if (hisgory)
// {
// hisgory = eval('(' + hisgory + ')');
// var history_str = '';
// for (key in hisgory)
// {
// if (hisgory[key])
// {
// arr = hisgory[key].split('|');
// history_str += '<li>';
// history_str += '<div class="goods_skim_tp"><a href="goods.php?id='+arr[0]+'"
// title="'+arr[2]+'" target="_blank"><img
// src="http://www.masamaso.com/upload/'+arr[3]+'_s_1.jpg" alt="'+arr[2]+'"
// /></a></div>';
// history_str += '<div class="goods_skim_txt gray9">';
// history_str += '<p><a href="goods.php?id='+arr[0]+'">'+arr[2]+'</a></p>';
// history_str += '<p class="goods_skim_price">￥'+arr[1]+'</p>';
// history_str += '</div>';
// history_str += '</li>';
// jQuery("#history_area").html(history_str);
// }
// }
// }
// }


function login_or_reg(type,return_url,callBack)
{
	//ajaxLoginOrRegist(type, return_url, callBack);
	
	//直接定位到用户中心的登录页面，将原来采用弹出层登录的方式去掉	
	var locationUrl = encodeURIComponent(return_url);
	location.href = USER_CENTER_URL + "/web/register/login.php?return_url=" + locationUrl;
    return;
	
    /*
	//原来的处理方式，采用弹出层来实现用户登录
    jQuery('#question').html('<div style="padding:50px;border:1px solid #E7E7E7;background:#FDFDFD;text-align:center;line-height:20px;"><p><img src="http://image.masamaso.com/loading.gif" onclick="jQuery.unblockUI();" alt="loading" /></p><p>数据加载中…… <a href="javascript:;" onclick="jQuery.unblockUI();">关闭</a></p></div>');

    jQuery.blockUI({
        message: jQuery('#question'), 
        css: {
            top:  (jQuery(window).height()-350) /2 + 'px',
            left: (jQuery(window).width()-420)/2 + 'px',
            cursor: 'text'
        }
    });
    jQuery.ajax({
        type:"POST",
        url:"/user_validate.php",
        cache:false,
        dataType:'json',     // 接受数据格式
        data:"type="+type+"&act=flow_login_reg&return_url="+return_url+'&callBack='+callBack,
        success:function (result){
            if (result.content == '' || result.content == undefined)
            {
                jQuery.unblockUI();
                if (result.url != '' && result.url != undefined) location.href = result.url;
            }
            else
            {
                if (typeof(result.error) == 'undefined' && window.GridsumWebDissector) {
                    var _gsTracker = GridsumWebDissector.getTracker("GWD-000409");
                    _gsTracker.track("/targetpage/regSuccess.html");
                }
                jQuery("#question").html(result.content);
            }
        },
        error:function (result){
        // alert('服务器错误！');
        }
    });
    */
}


/**
 * 配送地址用户的验证
 */
function valdate_customer(customer,key)
{
    if (customer != '')
    {
        jQuery.ajax({
            type:"POST",
            url:"/user_validate.php",
            cache:false,
            dataType:'json',     // 接受数据格式
            data:"customer="+customer+"&act=validate_customer",
            success:function (result){
                if (result.error == 1)
                {
                    jQuery("#email_msg_"+key).html(result.message+"，如果您是注册用户，请<a href=\"javascript:;\" onclick=\"login_or_reg('login','/shopping.php?c=order&a=address')\">登陆</a>。");
                    document.getElementById('submit_address').disabled = true;
                }
                else
                {
                    jQuery("#email_msg_"+key).html("");
                    document.getElementById('submit_address').disabled = false;
                }
            }
        });
    }
}
/**
 * 地址验证
 */
function validate_address(key,is_login)
{
    var customer = document.getElementById('customer_'+ key).value;
    var country = document.getElementById('country_'+ key).value;
    var province = document.getElementById('province_'+ key).value;
    var city = document.getElementById('city_'+ key).value;
    var districts = document.getElementById('districts_'+ key).value;
    var town = document.getElementById('town_'+ key).value;
    var address = document.getElementById('address_'+ key).value;
    var zipcode = document.getElementById('zipcode_'+ key).value;
    var code = document.getElementById('code_'+ key).value;
    var tel = document.getElementById('tel_'+ key).value;
    var tel_ext = document.getElementById('tel_ext_'+ key).value;
    var mobile = document.getElementById('mobile_'+ key).value;
    var email = document.getElementById('email_'+ key).value;
    var shipping_time = document.getElementById('shipping_time_'+ key);
    customer = customer.replace(/^\s+|\s+jQuery/g,"");
    if (customer == '')
    {
        alert('请输入收货人姓名！');
        return false;
    }

    if (country == '')
    {
        alert('请选择国家！');
        return false;
    }

    if (province == '')
    {
        alert('请选择省！');
        return false;
    }
    if (city == '')
    {
        alert('请选择市！');
        return false;
    }

    if (districts == '')
    {
    // alert('请选择区县！');return false;
    }

    if (town == '')
    {
    // alert('请选择街道！');return false;
    }
    // 只有北京时才可以选择区
    if (districts == '' && province == 2)
    {
    // alert('请选择区！');return false;
    }
    if (address.length < 4)
    {
        alert('详细地址不能少于四个汉字！');
        return false;
    }
    if(zipcode == '')
    {
        alert('请填写邮政编码！');
        return false;
    }
    if (shipping_time)
    {
        if (shipping_time.value == '')
        {
            shipping_time.focus();
            alert('请选择配送时间！');
            return false;
        }
    }

    if(mobile.length != 11)
    {
        alert('请填写正确的手机号！');
        return false;
    }
    if (!mobile.isMobile())
    {
        alert('请填写正确的手机号！');
        return false;
    }

    if ((code != '' || tel_ext) && tel == '')
    {
        alert('请填写电话号码！');
        return false;
    }

    if (mobile != '')
    {
        if (mobile.length < 11)
        {
            alert('手机号不能少于11位！');
            return false;
        }
    }
    if (tel != '')
    {
        if (tel.length != 8 && tel.length != 7)
        {
            alert('电话号码只可以是7位或8位数字！');
            return false;
        }
    }

    // 验证邮编的合法性
    if(zipcode.length!=6){
        alert('请填写正确的邮政编码！');
        return false;
    }
    else{
        var rexTel=/^[0-9]+jQuery/;
        if(!rexTel.test(zipcode)){
            alert('请填写正确的邮政编码！');
            return false;
        }
    }

    if (!Utils.isEmail(email))
    {
        alert('请填写正确的Email地址！');
        return false;
    }
    else
    {

    }
    if (is_login == 1)
    {
        var password = document.getElementById('password_'+key).value;
        var password1 = document.getElementById('password1_'+key).value;
        password = password.toString();
        password1 = password1.toString();
        if (password.length < 6)
        {
            alert('密码不能小于六位！');
            return false;
        }
        if (password != password1)
        {
            alert('两次填写的密码不一致！');
            return false;
        }
    }
    // else
    // {
    // jQuery.ajax({
    // type:"POST",
    // url:"user_validate.php",
    // cache:false,
    // dataType:'json', //接受数据格式
    // data:"customer="+customer+"&act=validate_customer",
    // success:function (result){
    // if (result.error == 1)
    // {
    // jQuery("#email_msg_"+key).html(result.message+"，如果您是注册用户，请<a
    // href=\"javascript:;\"
    // onclick=\"login_or_reg('login','flow.php?step=address')\">登陆</a>。");
    // document.getElementById('submit_address').disabled = true;
    // }
    // else
    // {
    // jQuery("#email_msg_"+key).html("");
    // document.getElementById('submit_address').disabled = false;
    // }
    // }
    // });
    // }

    // 检测用户的详细信息里是否有省市信息
    // if (document.getElementById('address_'+
    // key).value.indexOf(document.getElementById('city_'+
    // key).options[document.getElementById('city_'+ key).selectedIndex].text)
    // >= 0){
    //
    // } else document.getElementById('address_'+ key).value =
    // document.getElementById('city_'+
    // key).options[document.getElementById('city_'+
    // key).selectedIndex].text+"市"+document.getElementById('address_'+
    // key).value;
    // if (document.getElementById('address_'+
    // key).value.indexOf(document.getElementById('province_'+
    // key).options[document.getElementById('province_'+
    // key).selectedIndex].text) >= 0){
    //
    // } else document.getElementById('address_'+ key).value =
    // document.getElementById('province_'+
    // key).options[document.getElementById('province_'+
    // key).selectedIndex].text+"省"+document.getElementById('address_'+
    // key).value;

    return  true;

}

String.prototype.Trim = function() {
    var m = this.match(/^\s*(\S+(\s+\S+)*)\s*/);
    return (m == null) ? "" : m[1];
}

String.prototype.isMobile = function() {
    return (/^(?:1[3|5|8|4]\d)-?\d{5}(\d{3}|\*{3})/.test(this.Trim()));
}
/**
 * 配送地址城市联动菜单
 */
function change_city(parent_id,obj_id,districts_id,type)
{
    var arr = districts_id.split("_");
    var key = arr[1];
    var sel = document.getElementById(obj_id);
    jQuery('#'+districts_id).hide();
    sel.length = 0;
    create_option(sel,'','请选择');
    jQuery.ajax({
        type:"POST",
        url:"/flow.php",
        cache:false,
        dataType:'json',     // 接受数据格式
        data:"parent_id="+parent_id+"&step=change_region&type=" + type,
        success:function (result){
            sel.length = 0;
            if (result.error == 0)
            {
                /* 创建 options */
                var ad = result.content;
                if (ad)
                {
                    post_str = '';
                    for (i = 0; i < ad.length; i++)
                    {
                        post_str += '<input type="hidden" value="'+ad[i].post_code+'" id="post_'+ad[i].region_id+'"/><input type="hidden" value="'+ad[i].area_code+'" id="area_'+ad[i].region_id+'"/>';
                        create_option(sel,ad[i].region_id,ad[i].region_name);
                        if (type == 2)
                        {
                            jQuery('#'+obj_id).show();
                        }
                    }
                    // var objdiv = document.createElement("DIV");
                    // alert(objdiv);
                    // objdiv.id="post_code";
                    if (document.getElementById('post_code_'+key))
                    {
                        jQuery('#post_code_'+key).html(post_str);
                    // document.getElementById('post_code_'+key).innerHTML =
                    // post_str;
                    }

                }
            }
            else
            {
                if (type == 2)
                {
                    jQuery('#'+obj_id).hide();
                }
            }
        },
        error:function (result){
        // alert('服务器错误！');
        }
    });
}

/**
 * 创建新元素
 */
function create_option(obj,id,name)
{
    var opt = document.createElement("OPTION");
    opt.value = id;
    opt.text  = name;
    obj.options.add(opt);
}


// jQuery(document).ready(function(){
// if (document.getElementById('spanCount'))
// {
// //购物车提示弹窗
// setShoppingCar();
// jQuery("#spanCount").DMenu("#content");
// }
// if (document.getElementById('flowPrice'))
// {
// jQuery.ajax({
// type:"POST",
// url:"flow.php",
// cache:false,
// dataType:'json', //接受数据格式
// data:"step=header_cart_price",
// success:function (msg){
// if (msg.num != 0) {
// jQuery("#flowPrice").html("总金额：￥"+msg.price);
// jQuery("#flowNum").html(msg.num);
// }
// }
// });
// }
// });



(function(jQuery){
    jQuery.fn.extend({
        Scroll:function(opt,callback){
            // 参数初始化
            if(!opt) var opt={};
            var _btnUp = jQuery("#"+ opt.up);// Shawphy:向上按钮
            var _btnDown = jQuery("#"+ opt.down);// Shawphy:向下按钮
            var timerID;
            var _this=this.eq(0).find("ul:first");
            var     lineH=_this.find("li:first").height(), // 获取行高
            line=opt.line?parseInt(opt.line,10):parseInt(this.height()/lineH,10), // 每次滚动的行数，默认为一屏，即父容器高度
            speed=opt.speed?parseInt(opt.speed,10):500; // 卷动速度，数值越大，速度越慢（毫秒）
            timer=opt.timer // ?parseInt(opt.timer,10):3000; //滚动的时间间隔（毫秒）
            if(line==0) line=1;
            var upHeight=0-line*lineH;
            // 滚动函数
            var scrollUp=function(){
                _btnUp.unbind("click",scrollUp); // Shawphy:取消向上按钮的函数绑定
                _this.animate({
                    marginTop:upHeight
                },speed,function(){
                    for(i=1;i<=line;i++){
                        _this.find("li:first").appendTo(_this);
                    }
                    _this.css({
                        marginTop:0
                    });
                    _btnUp.bind("click",scrollUp); // Shawphy:绑定向上按钮的点击事件
                });

            }
            // Shawphy:向下翻页函数
            var scrollDown=function(){
                _btnDown.unbind("click",scrollDown);
                for(i=1;i<=line;i++){
                    _this.find("li:last").show().prependTo(_this);
                }
                _this.css({
                    marginTop:upHeight
                });
                _this.animate({
                    marginTop:0
                },speed,function(){
                    _btnDown.bind("click",scrollDown);
                });
            }
            // Shawphy:自动播放
            var autoPlay = function(){
                if(timer)timerID = window.setInterval(scrollUp,timer);
            };
            var autoStop = function(){
                if(timer)window.clearInterval(timerID);
            };
            autoPlay();
            // 鼠标事件绑定
            // _this.hover(autoStop,autoPlay).mouseout();
            _btnUp.css("cursor","pointer").click( scrollUp ).hover(autoStop,autoPlay);// Shawphy:向上向下鼠标事件绑定
            _btnDown.css("cursor","pointer").click( scrollDown ).hover(autoStop,autoPlay);

        }
    })
})(jQuery);

// 获取购物车内的物品数
function setShoppingCar()
{
    var cart_num = 0;
    var product_cookie = getCookie("product");
    var event_offers_cart_cookie = getCookie("event_offers_cart");
    if (product_cookie)
    {
        var product_cookie_obj = eval('(' + product_cookie + ')');
        for (var i in product_cookie_obj)
        {
            if (!isNaN(product_cookie_obj[i]['num']))
            {
                cart_num += parseInt(product_cookie_obj[i]['num']);
            }
        }
    }
    if (event_offers_cart_cookie)
    {
        var event_offers_cart_cookie_obj = eval('(' + event_offers_cart_cookie + ')');
        for (var i in event_offers_cart_cookie_obj)
        {
            if (event_offers_cart_cookie_obj[i]['event_product'])
            {
                for (var n; n <= event_offers_cart_cookie_obj[i]['event_product'].length;n++)
                {
                    if (!isNaN(event_offers_cart_cookie_obj[i]['event_product'][n]['num']))
                    {
                        cart_num += parseInt(event_offers_cart_cookie_obj[i]['event_product'][n]['num']);
                    }
                }

            }
        }
    }
    jQuery("#spanCount").html("<a href='/flow.php?step=flow' style='color:#fcf3cf;'>购物车中有<span style='color:red;font-weight:bold;'>"+(cart_num)+" </span>款商品</a>");
}

function GetLast2Prod()
{
    jQuery("#content").html("loading......");
    jQuery.ajax({
        type:"POST",
        url:"/flow.php",
        cache:false,
        dataType:'html',     // 接受数据格式
        data:"step=header_cart",
        success:function (msg){
            jQuery("#content").html("loding......");
            // alert(msg);
            jQuery('#content').html(msg);
        }
    });
}


function checkAll(e, itemName)
{
    var aa = document.getElementsByName(itemName);
    for (var i=0; i<aa.length; i++)
        aa[i].checked = e.checked;
}
function checkItem(e, allName)
{
    var all = document.getElementsByName(allName)[0];
    if(!e.checked) all.checked = false;
    else
    {
        var aa = document.getElementsByName(e.name);
        for (var i=0; i<aa.length; i++)
            if(!aa[i].checked) return;
        all.checked = true;
    }
}

/**
 * 验证时间格式 2009-02-11 00:00:00
 */
function strDateTime(str)
{
    var reg = /^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})jQuery/;
    var r = str.match(reg);
    if(r==null)return false;
    var d= new Date(r[1], r[3]-1,r[4],r[5],r[6],r[7]);
    return (d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4]&&d.getHours()==r[5]&&d.getMinutes()==r[6]&&d.getSeconds()==r[7]);
}

// 短时间，形如 (13:04:06)
function isTime(str)
{
    var a = str.match(/^(\d{1,2})(:)?(\d{1,2})\2(\d{1,2})jQuery/);
    if (a == null) {
        alert('输入的参数不是时间格式');
        return false;
    }
    if (a[1]>24 || a[3]>60 || a[4]>60)
    {
        alert("时间格式不对");
        return false
    }
    return true;
}

// 短日期，形如 (2003-12-05)
function strDate(str)
{
    var r = str.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})jQuery/);
    if(r==null)return false;
    var d= new Date(r[1], r[3]-1, r[4]);
    return (d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4]);
}
/**
 * 
 */
function check_date(id)
{
    var time = document.getElementById(id).value;
    if (time)
    {
        if (!strDateTime(time))
        {
            alert("您填写的时间格式不正确，时间格式应为：2009-02-11 00:00:00");
            document.getElementById(id).focus();
            document.getElementById(id).select();
            return false;
        }
    }
    return true;
}

function onlyNum()
{
    if(!(event.keyCode==46)&&!(event.keyCode==8)&&!(event.keyCode==37)&&!(event.keyCode==39))
        if(!((event.keyCode>=48&&event.keyCode<=57)||(event.keyCode>=96&&event.keyCode<=105)))
            event.returnValue=false;
    if (event.ctrlKey)
    {
        event.returnValue=true;
    }
}

function onlyPirce()
{
    if(!((event.keyCode>=48&&event.keyCode<=57)))
        event.returnValue=false;
}

/* jQueryId : utils.js 5052 2007-02-03 10:30:13Z weberliu jQuery */

var Browser = new Object();

Browser.isMozilla = (typeof document.implementation != 'undefined') && (typeof document.implementation.createDocument != 'undefined') && (typeof HTMLDocument != 'undefined');
Browser.isIE = window.ActiveXObject ? true : false;
Browser.isFirefox = (navigator.userAgent.toLowerCase().indexOf("firefox") != - 1);
Browser.isSafari = (navigator.userAgent.toLowerCase().indexOf("safari") != - 1);
Browser.isOpera = (navigator.userAgent.toLowerCase().indexOf("opera") != - 1);

var Utils = new Object();

Utils.htmlEncode = function(text)
{
    return text.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}

Utils.trim = function( text )
{
    if (typeof(text) == "string")
    {
        return text.replace(/^\s*|\s*jQuery/g, "");
    }
    else
    {
        return text;
    }
}

Utils.isEmpty = function( val )
{
    switch (typeof(val))
    {
        case 'string':
            return Utils.trim(val).length == 0 ? true : false;
            break;
        case 'number':
            return val == 0;
            break;
        case 'object':
            return val == null;
            break;
        case 'array':
            return val.length == 0;
            break;
        default:
            return true;
    }
}

Utils.isNumber = function(val)
{
    var reg = /^[\d|\.|,]+jQuery/;
    return reg.test(val);
}

Utils.isInt = function(val)
{
    if (val == "")
    {
        return false;
    }
    var reg = /\D+/;
    return !reg.test(val);
}

Utils.isEmail = function( email )
{
    var reg1 = /([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)/;

    return reg1.test( email );
}

Utils.isTel = function ( tel )
{
    var reg = /^[\d|\-|\s|\_]+jQuery/; // 只允许使用数字-空格等

    return reg.test( tel );
}

Utils.fixEvent = function(e)
{
    var evt = (typeof e == "undefined") ? window.event : e;
    return evt;
}

Utils.srcElement = function(e)
{
    if (typeof e == "undefined") e = window.event;
    var src = document.all ? e.srcElement : e.target;

    return src;
}

Utils.isTime = function(val)
{
    var reg = /^\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}jQuery/;

    return reg.test(val);
}

function rowindex(tr)
{
    if (Browser.isIE)
    {
        return tr.rowIndex;
    }
    else
    {
        table = tr.parentNode.parentNode;
        for (i = 0; i < table.rows.length; i ++ )
        {
            if (table.rows[i] == tr)
            {
                return i;
            }
        }
    }
}

document.getCookie = function(sName)
{
    // cookies are separated by semicolons
    var aCookie = document.cookie.split("; ");
    for (var i=0; i < aCookie.length; i++)
    {
        // a name/value pair (a crumb) is separated by an equal sign
        var aCrumb = aCookie[i].split("=");
        if (sName == aCrumb[0])
            return decodeURIComponent(aCrumb[1]);
    }

    // a cookie with the requested name does not exist
    return null;
}

document.setCookie = function(sName, sValue, sExpires)
{
    var sCookie = sName + "=" + encodeURIComponent(sValue);
    if (sExpires != null)
    {
        sCookie += "; expires=" + sExpires;
    }

    document.cookie = sCookie;
}

document.removeCookie = function(sName,sValue)
{
    document.cookie = sName + "=; expires=Fri, 31 Dec 1999 23:59:59 GMT;";
}

function getPosition(o)
{
    var t = o.offsetTop;
    var l = o.offsetLeft;
    while(o = o.offsetParent)
    {
        t += o.offsetTop;
        l += o.offsetLeft;
    }
    var pos = {
        top:t,
        left:l
    };
    return pos;
}

function cleanWhitespace(element)
{
    var element = element;
    for (var i = 0; i < element.childNodes.length; i++) {
        var node = element.childNodes[i];
        if (node.nodeType == 3 && !/\S/.test(node.nodeValue))
            element.removeChild(node);
    }
}

/*******************************************************************************
 * 2010-3-6 图片轮播
 ******************************************************************************/
var PImgPlayer = {
    _timer : null,
    _items : [],
    _container : null,
    _index : 0,
    _imgs : [],
    intervalTime : 3500,
    init : function( objID, w, h, time ){
        this.intervalTime = time || this.intervalTime;
        this._container = document.getElementById( objID );
        this._container.style.display = "block";
        this._container.style.width = w + "px";
        this._container.style.height = h + "px";
        this._container.style.position = "relative";
        this._container.style.overflow = "hidden";
        // this._container.style.border = "1px solid #fff";
        var linkStyle = "display: block; TEXT-DECORATION: none;";
        if( document.all ){
            linkStyle += "FILTER:";
            linkStyle += "progid:DXImageTransform.Microsoft.Barn(duration=0.5, motion='out', orientation='vertical') ";
            linkStyle += "progid:DXImageTransform.Microsoft.Barn ( duration=0.5,motion='out',orientation='horizontal') ";
            linkStyle += "progid:DXImageTransform.Microsoft.Blinds ( duration=0.5,bands=10,Direction='down' )";
            linkStyle += "progid:DXImageTransform.Microsoft.CheckerBoard()";
            linkStyle += "progid:DXImageTransform.Microsoft.Fade(duration=0.5,overlap=0)";
            linkStyle += "progid:DXImageTransform.Microsoft.GradientWipe ( duration=1,gradientSize=1.0,motion='reverse' )";
            linkStyle += "progid:DXImageTransform.Microsoft.Inset ()";
            linkStyle += "progid:DXImageTransform.Microsoft.Iris ( duration=1,irisStyle=PLUS,motion=out )";
            linkStyle += "progid:DXImageTransform.Microsoft.Iris ( duration=1,irisStyle=PLUS,motion=in )";
            linkStyle += "progid:DXImageTransform.Microsoft.Iris ( duration=1,irisStyle=DIAMOND,motion=in )";
            linkStyle += "progid:DXImageTransform.Microsoft.Iris ( duration=1,irisStyle=SQUARE,motion=in )";
            linkStyle += "progid:DXImageTransform.Microsoft.Iris ( duration=0.5,irisStyle=STAR,motion=in )";
            linkStyle += "progid:DXImageTransform.Microsoft.RadialWipe ( duration=0.5,wipeStyle=CLOCK )";
            linkStyle += "progid:DXImageTransform.Microsoft.RadialWipe ( duration=0.5,wipeStyle=WEDGE )";
            linkStyle += "progid:DXImageTransform.Microsoft.RandomBars ( duration=0.5,orientation=horizontal )";
            linkStyle += "progid:DXImageTransform.Microsoft.RandomBars ( duration=0.5,orientation=vertical )";
            linkStyle += "progid:DXImageTransform.Microsoft.RandomDissolve ()";
            linkStyle += "progid:DXImageTransform.Microsoft.Spiral ( duration=0.5,gridSizeX=16,gridSizeY=16 )";
            linkStyle += "progid:DXImageTransform.Microsoft.Stretch ( duration=0.5,stretchStyle=PUSH )";
            linkStyle += "progid:DXImageTransform.Microsoft.Strips ( duration=0.5,motion=rightdown )";
            linkStyle += "progid:DXImageTransform.Microsoft.Wheel ( duration=0.5,spokes=8 )";
            linkStyle += "progid:DXImageTransform.Microsoft.Zigzag ( duration=0.5,gridSizeX=4,gridSizeY=40 ); width: 100%; height: 100%";
        }
        //
        var ulStyle = "margin:0;width:"+w+"px;position:absolute;z-index:999;FILTER:Alpha(Opacity=50,FinishOpacity=50, Style=1);overflow: hidden;bottom:1px;height:16px; border-right:1px solid #fff;";
        //
        var liStyle = "margin:0;list-style-type: none; margin:0;padding:0; float:right;";
        //
        var baseSpacStyle = "clear:both; display:block; width:15px;line-height:16px; font-size:12px; FONT-FAMILY:'����';opacity: 0.6;";
        baseSpacStyle += "border:1px solid #fff;border-right:0;border-bottom:0;";
        baseSpacStyle += "color:#fff;text-align:center; cursor:pointer; ";
        //
        var ulHTML = "";
        if (this._items.length > 1) {
            for(var i = this._items.length -1; i >= 0; i--){
                var spanStyle = "";
                if( i==this._index ){
                    spanStyle = baseSpacStyle + "background:#1C6EA7;";
                } else {
                    spanStyle = baseSpacStyle + "background:#000;";
                }
                ulHTML += "<li style=\""+liStyle+"\">";
                ulHTML += "<span onmouseover=\"PImgPlayer.mouseOver(this);\" onmouseout=\"PImgPlayer.mouseOut(this);\" style=\""+spanStyle+"\" onclick=\"PImgPlayer.play("+i+");return false;\" herf=\"javascript:;\" title=\"" + this._items[i].title + "\">" + (i+1) + "</span>";
                ulHTML += "</li>";
            }
        }
        //
        var html = "<a href=\""+this._items[this._index].link+"\" title=\""+this._items[this._index].title+"\" target=\"_blank\" style=\""+linkStyle+"\"></a><ul style=\""+ulStyle+"\">"+ulHTML+"</ul>";
        this._container.innerHTML = html;
        var link = this._container.getElementsByTagName("A")[0];
        link.style.width = w + "px";
        link.style.height = h + "px";
        link.style.background = 'url(' + this._items[0].img + ') no-repeat center center';
        //
        this._timer = setInterval( "PImgPlayer.play()", this.intervalTime );
    },
    addItem : function( _title, _link, _imgURL ){
        this._items.push ( {
            title:_title, 
            link:_link, 
            img:_imgURL
        } );
        var img = new Image();
        img.src = _imgURL;
        this._imgs.push( img );
    },
    play : function( index ){
        if (document.getElementById("na_num").value == 1) return false;
        if( index!=null ){
            this._index = index;
            clearInterval( this._timer );
            this._timer = setInterval( "PImgPlayer.play()", this.intervalTime );
        } else {
            this._index = this._index<this._items.length-1 ? this._index+1 : 0;
        }
        var link = this._container.getElementsByTagName("A")[0];
        if(link.filters){
            var ren = Math.floor(Math.random()*(link.filters.length));
            link.filters[ren].Apply();
            link.filters[ren].play();
        }
        link.href = this._items[this._index].link;
        link.title = this._items[this._index].title;
        link.style.background = 'url(' + this._items[this._index].img + ') no-repeat center center';
        //
        var liStyle = "margin:0;list-style-type: none; margin:0;padding:0; float:right;";
        var baseSpacStyle = "clear:both; display:block; width:15px;line-height:16px; font-size:12px; opacity: 0.6;";
        baseSpacStyle += "border:1px solid #fff;border-right:0;border-bottom:0;";
        baseSpacStyle += "color:#fff;text-align:center; cursor:pointer; ";
        var ulHTML = "";
        for(var i = this._items.length -1; i >= 0; i--){
            var spanStyle = "";
            if( i==this._index ){
                spanStyle = baseSpacStyle + "background:#1C6EA7;";
            } else {
                spanStyle = baseSpacStyle + "background:#000;";
            }
            ulHTML += "<li style=\""+liStyle+"\">";
            ulHTML += "<span onmouseover=\"PImgPlayer.mouseOver(this);\" onmouseout=\"PImgPlayer.mouseOut(this);\" style=\""+spanStyle+"\" onclick=\"PImgPlayer.play("+i+");return false;\" herf=\"javascript:;\" title=\"" + this._items[i].title + "\">" + (i+1) + "</span>";
            ulHTML += "</li>";
        }
        this._container.getElementsByTagName("UL")[0].innerHTML = ulHTML;
    },
    mouseOver : function(obj){
        var i = parseInt( obj.innerHTML );
        if( this._index!=i-1){
            obj.style.color = "#1C6EA7";
        }
    },
    mouseOut : function(obj){
        obj.style.color = "#fff";
    }
}


/*******************************************************************************
 * 2010-3-6 下拉菜单
 ******************************************************************************/
var selects = document.getElementsByTagName('select');
var isIE = (document.all && window.ActiveXObject && !window.opera) ? true : false;

function jQuerym(id) {
    return document.getElementById(id);
}

function stopBubbling (ev) {
    ev.stopPropagation();
}
function rSelects() {
    for (i=0;i<selects.length;i++){
        if ((i>0) || (location.href.indexOf('flow') >= 0)) continue;
        selects[i].style.display = 'none';
        select_tag = document.createElement('div');
        select_tag.id = 'select_' + selects[i].name;
        select_tag.className = 'select_box';
        selects[i].parentNode.insertBefore(select_tag,selects[i]);

        select_info = document.createElement('div');
        select_info.id = 'select_info_' + selects[i].name;
        select_info.className='tag_select';
        select_info.style.cursor='pointer';
        select_tag.appendChild(select_info);

        select_ul = document.createElement('ul');
        select_ul.id = 'options_' + selects[i].name;
        select_ul.className = 'tag_options';
        select_ul.style.position='absolute';
        select_ul.style.display='none';
        select_ul.style.zIndex='999';
        select_tag.appendChild(select_ul);

        rOptions(i,selects[i].name);

        mouseSelects(selects[i].name);

        if (isIE){
            selects[i].onclick = new Function("clickLabels3('"+selects[i].name+"');window.event.cancelBubble = true;");
        }
        else if(!isIE){
            selects[i].onclick = new Function("clickLabels3('"+selects[i].name+"')");
            selects[i].addEventListener("click", stopBubbling, false);
        }
    }
}
function rOptions(i, name) {
    var options = selects[i].getElementsByTagName('option');
    var options_ul = 'options_' + name;
    for (n=0;n<selects[i].options.length;n++){
        option_li = document.createElement('li');
        option_li.style.cursor='pointer';
        option_li.className='open';
        jQuerym(options_ul).appendChild(option_li);

        option_text = document.createTextNode(selects[i].options[n].text);
        option_li.appendChild(option_text);

        option_selected = selects[i].options[n].selected;

        if(option_selected){
            option_li.className='open_selected';
            option_li.id='selected_' + name;
            jQuerym('select_info_' + name).appendChild(document.createTextNode(option_li.innerHTML));
        }

        option_li.onmouseover = function(){
            this.className='open_hover';
        }
        option_li.onmouseout = function(){
            if(this.id=='selected_' + name){
                this.className='open_selected';
            }
            else {
                this.className='open';
            }
        }

        option_li.onclick = new Function("clickOptions("+i+","+n+",'"+selects[i].name+"')");
    }
}
function mouseSelects(name){
    var sincn = 'select_info_' + name;

    jQuerym(sincn).onmouseover = function(){
        if(this.className=='tag_select') this.className='tag_select_hover';
    }
    jQuerym(sincn).onmouseout = function(){
        if(this.className=='tag_select_hover') this.className='tag_select';
    }

    if (isIE){
        jQuerym(sincn).onclick = new Function("clickSelects('"+name+"');window.event.cancelBubble = true;");
    }
    else if(!isIE){
        jQuerym(sincn).onclick = new Function("clickSelects('"+name+"');");
        jQuerym('select_info_' +name).addEventListener("click", stopBubbling, false);
    }

}
function clickSelects(name){
    var sincn = 'select_info_' + name;
    var sinul = 'options_' + name;
    for (i=0;i<selects.length;i++){
        if ((i>0) || (location.href.indexOf('flow') >= 0)) continue;
        if(selects[i].name == name){
            if( jQuerym(sincn).className =='tag_select_hover'){
                jQuerym(sincn).className ='tag_select_open';
                jQuerym(sinul).style.display = '';
            }
            else if( jQuerym(sincn).className =='tag_select_open'){
                jQuerym(sincn).className = 'tag_select_hover';
                jQuerym(sinul).style.display = 'none';
            }
        }
        else{
            jQuerym('select_info_' + selects[i].name).className = 'tag_select';
            jQuerym('options_' + selects[i].name).style.display = 'none';
        }
    }

}
function clickOptions(i, n, name){
    var li = jQuerym('options_' + name).getElementsByTagName('li');

    jQuerym('selected_' + name).className='open';
    jQuerym('selected_' + name).id='';
    li[n].id='selected_' + name;
    li[n].className='open_hover';
    jQuerym('select_' + name).removeChild(jQuerym('select_info_' + name));

    select_info = document.createElement('div');
    select_info.id = 'select_info_' + name;
    select_info.className='tag_select';
    select_info.style.cursor='pointer';
    jQuerym('options_' + name).parentNode.insertBefore(select_info,jQuerym('options_' + name));

    mouseSelects(name);

    jQuerym('select_info_' + name).appendChild(document.createTextNode(li[n].innerHTML));
    jQuerym( 'options_' + name ).style.display = 'none' ;
    jQuerym( 'select_info_' + name ).className = 'tag_select';
    selects[i].options[n].selected = 'selected';

}
function gl_set() {
// var mh_url = location.href;
// if (mh_url.indexOf('index') >= 0) {
// document.getElementById('menu_m0').className = 'm0';
// }
// else if (mh_url.indexOf('category') >= 0) {
// if (document.getElementById('parent_id')) {
// var par_id = document.getElementById('parent_id').value;
// if (par_id == 330) document.getElementById('menu_m1').className = 'm1';
// if (par_id == 333) document.getElementById('menu_m2').className = 'm2';
// if (par_id == 334) document.getElementById('menu_m3').className = 'm3';
// if (par_id == 368) document.getElementById('menu_m4').className = 'm4';
// if (par_id == 336) document.getElementById('menu_m5').className = 'm5';
// if (par_id == 337) document.getElementById('menu_m6').className = 'm6';
// if (par_id == 339) document.getElementById('menu_m7').className = 'm7';
// if (par_id == 340) document.getElementById('menu_m8').className = 'm8';
// if (par_id == 362) document.getElementById('menu_m9').className = 'm9';
// if (par_id == 411) document.getElementById('menu_m10').className = 'm10';
// if (par_id == 345) document.getElementById('menu_m11').className = 'm11';
// }
// }
}
// window.onload = function(e) {
// bodyclick = document.getElementsByTagName('body').item(0);
// rSelects();
// bodyclick.onclick = function(){
// for (i=0;i<selects.length;i++){
// jQuerym('select_info_' + selects[i].name).className = 'tag_select';
// jQuerym('options_' + selects[i].name).style.display = 'none';
// }
// }
// }

// 新的选择城市（五级城市）
function change_delivery_zone(inputid,typeid){
    var param = "";
    var zone_arr = inputid.split("_");

    var d_name = "";
    var t_name = "";

    // if(typeid!=""){
    if(zone_arr[0]=="city"){
        param = "&provinceid="+jQuery("#province_"+zone_arr[1]).val();
        jQuery("#zone_address_info_"+zone_arr[1]).html("");
        jQuery("#zone_address_info_"+zone_arr[1]).html(jQuery("#province_"+zone_arr[1]+" option:selected").text()+jQuery("#city_"+zone_arr[1]+" option:selected").text());
        jQuery("#zone_address_"+zone_arr[1]).val("");
        jQuery("#zone_address_"+zone_arr[1]).val(jQuery("#province_"+zone_arr[1]+" option:selected").text()+jQuery("#city_"+zone_arr[1]+" option:selected").text()+"-");
    }
    if(zone_arr[0]=="districts"){
        param = "&provinceid="+jQuery("#province_"+zone_arr[1]).val()+"&cityid="+jQuery("#city_"+zone_arr[1]).val();

        if(jQuery("#districts_"+zone_arr[1]).val()){
            var d_name = jQuery("#districts_"+zone_arr[1]+" option:selected").text();
        }

        jQuery("#zone_address_info_"+zone_arr[1]).html("");
        jQuery("#zone_address_info_"+zone_arr[1]).html(jQuery("#province_"+zone_arr[1]+" option:selected").text()+jQuery("#city_"+zone_arr[1]+" option:selected").text()+d_name);
        jQuery("#zone_address_"+zone_arr[1]).val("");
        jQuery("#zone_address_"+zone_arr[1]).val(jQuery("#province_"+zone_arr[1]+" option:selected").text()+jQuery("#city_"+zone_arr[1]+" option:selected").text()+d_name+"-");
    }

    if(zone_arr[0]=="town"){
        param = "&districtsid="+jQuery("#districts_"+zone_arr[1]).val();

        if(jQuery("#districts_"+zone_arr[1]).val()){
            var d_name = jQuery("#districts_"+zone_arr[1]+" option:selected").text();
        }

        if(jQuery("#town_"+zone_arr[1]).val()!=""){
            var t_name = jQuery("#town_"+zone_arr[1]+" option:selected").text();
        }

        jQuery("#zone_address_info_"+zone_arr[1]).html("");
        jQuery("#zone_address_info_"+zone_arr[1]).html(jQuery("#province_"+zone_arr[1]+" option:selected").text()+jQuery("#city_"+zone_arr[1]+" option:selected").text()+d_name+t_name);
        jQuery("#zone_address_"+zone_arr[1]).val("");
        jQuery("#zone_address_"+zone_arr[1]).val(jQuery("#province_"+zone_arr[1]+" option:selected").text()+jQuery("#city_"+zone_arr[1]+" option:selected").text()+d_name+t_name+"-");
    }
    jQuery.ajax({
        type:"POST",
        url:"/delivery_zone.php",
        cache:false,
        data:"step=get_address_info&zone_type="+zone_arr[0]+"&zone_id="+typeid+param,
        success:function (msg){
            if(zone_arr[0]=="country"){
                jQuery("#province_"+zone_arr[1]).html("");
                jQuery("#province_"+zone_arr[1]).html(msg);
            }else if(zone_arr[0]=="province"){
                jQuery("#city_"+zone_arr[1]).html("");
                jQuery("#city_"+zone_arr[1]).html(msg);
            }else if(zone_arr[0]=="city"){
                jQuery("#districts_"+zone_arr[1]).html("");
                jQuery("#districts_"+zone_arr[1]).html(msg);
                jQuery("#town_"+zone_arr[1]).html("");
                jQuery("#town_"+zone_arr[1]).html('<option value="">请选择街道</option>');
            }else if(zone_arr[0]=="districts"){
                jQuery("#town_"+zone_arr[1]).html("");
                jQuery("#town_"+zone_arr[1]).html(msg);
            }else if(zone_arr[0]=="town"){
                jQuery("#zipcode_"+zone_arr[1]).val("");
                jQuery("#zipcode_"+zone_arr[1]).val(msg);
            }
        }
    });

// }
}


/**
 * 地址管理中的地址验证
 */
function validate_address_user_manage()
{
    var customer = document.getElementById('customer').value;
    var country = document.getElementById('country').value;
    var province = document.getElementById('province').value;
    var city = document.getElementById('city').value;
    var districts = document.getElementById('districts').value;
    var town = document.getElementById('town').value;
    var address = document.getElementById('address').value;
    var zipcode = document.getElementById('zipcode').value;
    var code = document.getElementById('code').value;
    var tel = document.getElementById('tel').value;
    var tel_ext = document.getElementById('tel_ext').value;
    var mobile = document.getElementById('mobile').value;
    var email = document.getElementById('email').value;
    var shipping_time = document.getElementById('shipping_time');
    if (customer == '')
    {
        alert('请输入收货人姓名！');
        return false;
    }

    if (country == '')
    {
        alert('请选择国家！');
        return false;
    }

    if (province == '')
    {
        alert('请选择省！');
        return false;
    }
    if (city == '')
    {
        alert('请选择市！');
        return false;
    }

    if (districts == '')
    {
    // alert('请选择区县！');return false;
    }

    if (town == '')
    {
    // alert('请选择街道！');return false;
    }
    // 只有北京时才可以选择区
    if (districts == '' && province == 2)
    {
    // alert('请选择区！');return false;
    }
    if (address.length < 4)
    {
        alert('详细地址不能少于四个汉字！');
        return false;
    }
    if(zipcode == '')
    {
        alert('请填写邮政编码！');
        return false;
    }
    if (shipping_time)
    {
        if (shipping_time.value == '')
        {
            shipping_time.focus();
            alert('请选择配送时间！');
            return false;
        }
    }

    if(mobile.length != 11)
    {
        alert('请填写正确的手机号！');
        return false;
    }
    if (!mobile.isMobile())
    {
        alert('请填写正确的手机号！');
        return false;
    }

    if ((code != '' || tel_ext) && tel == '')
    {
        alert('请填写电话号码！');
        return false;
    }

    if (mobile != '')
    {
        if (mobile.length < 11)
        {
            alert('手机号不能少于11位！');
            return false;
        }
    }
    if (tel != '')
    {
        if (tel.length != 8 && tel.length != 7)
        {
            alert('电话号码只可以是7位或8位数字！');
            return false;
        }
    }

    // 验证邮编的合法性
    if(zipcode.length!=6){
        alert('请填写正确的邮政编码！');
        return false;
    }
    else{
        var rexTel=/^[0-9]+jQuery/;
        if(!rexTel.test(zipcode)){
            alert('请填写正确的邮政编码！');
            return false;
        }
    }

    if (!Utils.isEmail(email))
    {
        alert('请填写正确的Email地址！');
        return false;
    }
    else
    {

    }
    if (is_login == 1)
    {
        var password = document.getElementById('password_'+key).value;
        var password1 = document.getElementById('password1_'+key).value;
        password = password.toString();
        password1 = password1.toString();
        if (password.length < 6)
        {
            alert('密码不能小于六位！');
            return false;
        }
        if (password != password1)
        {
            alert('两次填写的密码不一致！');
            return false;
        }
    }

    return  true;

}

// 地址管理中的新的选择城市（五级城市）
function change_delivery_zone_user_manage(inputid,typeid){
    var param = "";
    var zone_arr = inputid;

    var d_name = "";
    var t_name = "";

    // if(typeid!=""){
    if(zone_arr=="city"){
        param = "&provinceid="+jQuery("#province").val();
        jQuery("#zone_address_info").html("");
        jQuery("#zone_address_info").html(jQuery("#province"+" option:selected").text()+jQuery("#city"+" option:selected").text());
        jQuery("#zone_address").val("");
        jQuery("#zone_address").val(jQuery("#province"+" option:selected").text()+jQuery("#city"+" option:selected").text()+"-");
    }
    if(zone_arr=="districts"){
        param = "&provinceid="+jQuery("#province").val()+"&cityid="+jQuery("#city").val();

        if(jQuery("#districts").val()!=""){
            var d_name = jQuery("#districts"+" option:selected").text();
        }
        jQuery("#zone_address_info").html("");
        jQuery("#zone_address_info").html(jQuery("#province"+" option:selected").text()+jQuery("#city"+" option:selected").text()+d_name);
        jQuery("#zone_address").val("");
        jQuery("#zone_address").val(jQuery("#province"+" option:selected").text()+jQuery("#city"+" option:selected").text()+d_name+"-");
    }
    if(zone_arr=="town"){
        param = "&districtsid="+jQuery("#districts").val();

        if(jQuery("#districts").val()!=""){
            var d_name = jQuery("#districts"+" option:selected").text();
        }

        if(jQuery("#town").val()!=""){
            var t_name = jQuery("#town"+" option:selected").text();
        }

        jQuery("#zone_address_info").html("");
        jQuery("#zone_address_info").html(jQuery("#province"+" option:selected").text()+jQuery("#city"+" option:selected").text()+d_name+t_name);
        jQuery("#zone_address").val("");
        jQuery("#zone_address").val(jQuery("#province"+" option:selected").text()+jQuery("#city"+" option:selected").text()+d_name+t_name+"-");
    }
    jQuery.ajax({
        type:"POST",
        url:"/delivery_zone.php",
        cache:false,
        data:"step=get_address_info&zone_type="+zone_arr+"&zone_id="+typeid+param,
        success:function (msg){
            if(zone_arr=="country"){
                jQuery("#province").html("");
                jQuery("#province").html(msg);
            }else if(zone_arr=="province"){
                jQuery("#city").html("");
                jQuery("#city").html(msg);
            }else if(zone_arr=="city"){
                jQuery("#districts").html("");
                jQuery("#districts").html(msg);
                jQuery("#town").html("");
                jQuery("#town").html('<option value="">请选择街道</option>');
            }else if(zone_arr=="districts"){
                jQuery("#town").html("");
                jQuery("#town").html(msg);
            }else if(zone_arr=="town"){
                jQuery("#zipcode").val("");
                jQuery("#zipcode").val(msg);
            }
        }
    });

// }
}
/*******************************************************************************
 * 2010-3-6 下拉菜单 end
 ******************************************************************************/
// 字符串格式的时间转化为date格式
function strToDate(str,ext){
    if(str==null || str=='') return;
    var arys = new Array();
    arys = str.split('-');
    var newDate = new Date(arys[0],arys[1]-1,arys[2],9,0,0);
    if(ext){
        newDate = new Date(newDate.getTime()+1000*60*60*24);
    }
    return newDate;
}
// 在一个时间段里显示指定的文字str
function showit(str,start,end){
    var date = new Date();
    var start=strToDate(start);
    var end=strToDate(end,false);
    if(date>start && date<end || start==null){
        document.write(str);
    }
}

function connectToClient(url){
    createNoneIframe('ssoIframe_');
    document.getElementById('ssoIframe_').src = url;
}
function createNoneIframe(tagName){
    if(document.getElementById(tagName)) return true;
    var _iframe = document.createElement('iframe');
    _iframe.name = tagName;
    _iframe.id = tagName;
    _iframe.style.display = 'none';
    document.body.appendChild(_iframe);
}

function _loadGgpub(source_id,ad_id){
    jQuery('#'+source_id+' script').remove()
    jQuery('#'+ad_id).html(jQuery('#'+source_id).html());
    jQuery('#'+source_id).remove();
}
/**
 * 如果是从联盟或联盟分账过来的流量则把COOKIE同步
 */
var syncUnionCookie = {
    current_host : document.domain,
    // 这里是联盟的
    getUnion : function (){
        if(this.current_host.match('dev.com')){
            return 'http://union.dev.com/api/sharekey.php?t='+Math.random();
        }else if(this.current_host.match('masa.test')){
            return 'http://union.test.com/api/sharekey.php?t='+Math.random();
        }else if (this.current_host.match('www2.')){
            return 'http://union.test.com/api/sharekey.php?t='+Math.random();
        }else if (this.current_host.match('test.')){
            return 'http://union1.masamaso.com/api/sharekey.php?t='+Math.random();
        }else if (this.current_host.match('www.')){
            return 'http://union.masamaso.com/api/sharekey.php?t='+Math.random();
        }
        return false;
    },// 这里是联盟分账的
    getUnionInterface : function (){
        return 'http://'+document.domain+'/api/sharekey.php?t='+Math.random();
    },
    getServerUrl : function(){
        var url = '';
        switch(syncUnionCookie.syncSwitch()){
            case 'union':
                url = syncUnionCookie.getUnion();
                break;
            case 'interface':
                url = syncUnionCookie.getUnionInterface();
                break;
        }
        return url;
    },
    getClientUrl :　function (){
        var rand = Math.random();
        if(this.current_host.match('dev.com')){
            return new Array('http://'+this.current_host+'/syncUnionCookie.php?T='+rand);
        }else if(this.current_host.match('masa.test')){
            return new Array('http://'+this.current_host+'/syncUnionCookie.php?T='+rand);
        }else if(this.current_host.match('test.')){
            return new Array('http://test.masamaso.com/syncUnionCookie.php?T='+rand,'http://test.vivian.cn/syncUnionCookie.php?T='+rand);
        }
        else if (this.current_host.match('www2.')){
            return new Array('http://www2.masamaso.com/syncUnionCookie.php?T='+rand,'http://www2.vivian.cn/syncUnionCookie.php?T='+rand);
        }else if (this.current_host.match('www.')){
            return new Array('http://www.masamaso.com/syncUnionCookie.php?T='+rand,'http://www.vivian.cn/syncUnionCookie.php?T='+rand);
        }
        return new Array('http://'+this.current_host+'/syncUnionCookie.php?T='+rand);
    },
    syncSwitch : function(){
        if(getArgs().referrer == 'union'){
            return 'union';
        }else if(getArgs().referrer == 'interface'){
            return 'interface';
        }
        return false;
    },
    syncCookie : function (){
        var serverUrl = syncUnionCookie.getServerUrl();
        if(serverUrl == '') return false;
        jQuery.getScript(syncUnionCookie.getServerUrl(),function(){
            var T = window.setInterval(function(){
                if(union_val && union_val != undefined && union_val != ''){
                    window.clearInterval(T);
                    var client = syncUnionCookie.getClientUrl();
                    for(var i=0;i < client.length;i++){
                        jQuery.getScript(client[i]+'&union_cookie_value='+encodeURIComponent(union_val));
                    }
                }
            }, 500);
        })
        
    },
    init : function (){
        if(syncUnionCookie.syncSwitch()){
            syncUnionCookie.syncCookie();
            return true;
        }
        return false;
    }
}
// 用来获得GET值
function getArgs(){
    var args = new Object( );
    var query = location.search.substring(1);     // Get query string
    var pairs = query.split("&");                 // Break at ampersand
    for(var i = 0; i < pairs.length; i++) {
        var pos = pairs[i].indexOf('=');          // Look for "name=value"
        if (pos == -1) continue;                  // If not found, skip
        var argname = pairs[i].substring(0,pos);  // Extract the name
        var value = pairs[i].substring(pos+1);    // Extract the value
        value = decodeURIComponent(value);        // Decode it, if needed
        args[argname] = value;                    // Store as a property
    }
    return args;                                  // Return the object
}


var sso = {
    default_url : document.location.href,
    login:function(num){
        var check = num || 0;
        var url = '/sso.php?do=login&check='+check+'&returnUrl='+encodeURI(sso.default_url.replace(/sso=true|\?sso=true/g,''))+'&t='+Math.random();
        connectToClient(url);
    },
    logout:function(num){
        var check = num || 0;
        var url = '/sso.php?do=logout&check='+check+'&returnUrl='+encodeURI(sso.default_url.replace(/sso=true|\?sso=true/g,''))+'&t='+Math.random();
        connectToClient(url);
    }
}

var GridsumSnapshotID = 0;

jQuery(document.body).ready(function(){
    // 如果没有加载 Web Dissecto JS 则加载文件
    if(!window._gsTracker){
        (function(){
            var s = document.createElement('script');
            s.type = 'text/javascript';
            s.async = true;
             //s.src = 'http://www.webdissector.com/js/Clients/GWD-000409-B86EA4/gs.js';
             //因国双启用CDN 所以连接修改为如下方式
            s.src= (location.protocol == 'https:' ? 'https://ssl.' : 'http://static.') + 'gridsumdissector.com/js/Clients/GWD-000409-B86EA4/gs.js';
           
            var firstScript = document.getElementsByTagName('script')[0];
            firstScript.parentNode.insertBefore(s, firstScript);
        })();
    }
})

function masaTrackSiteSearch(keywords){
    var T = window.setInterval(function(){
        if(window._gsTracker){
            _gsTracker. trackSiteSearch(keywords,"","utf8",false);// 其中kwd请用动态生成，填入实际的搜索词
            _gsTracker. bindSearchResults("goods_list");
            window.clearInterval(T);
        }
    }, 50)
    
}



function allyesListenLoginOrReg(customerID,nreg){

    var s={};
    s.keywords=""; //站内搜索关键字
    s.userid=customerID; //用户ID
    s.nreg=nreg; //是否新注册用户，1（是）和0（否）

    try {
        var idgTracker = _alysP.init("idiggerbjsem", "T-000010-01");
        idgTracker._setTrackPath('http://idigger.allyes.com/main/adftrack');
        idgTracker._setECM(s);
        idgTracker._setLinkClick(true);
        idgTracker._trackPoint();
    } catch(err) {}

}

function order_common(order,satus){
    if(jQuery('#mess_'+order).css('display') == 'none'){
        //一部调用订单 商品
        jQuery.ajax({
            url:'/user_order_product.php',
            type: "POST",
            dataType:'html',
            data:({
                orderId:order,
                act:'',
                status:satus
            }),
            success: function(data){
                jQuery('#mess_'+order).html(data);   
            }
        });
        jQuery('#mess_'+order).css('display','');
    }else{
        jQuery('#mess_'+order).css('display','none');
    };
}


jQuery(document.body).ready(function(){
    //同步联盟信息
    syncUnionCookie.init()
    //如果get sso等于true则执行sso
    if(getArgs().sso == 'true'){
        sso.login(0);
    }  
})

 function _gsFav(goods,number,size,price,pos){
        if(window._gsTracker){
            var _gsGoods = goods || '-';
            var _gsNumber=number || '-';
            var _gsSize=size || '-' ;
            var _gsPrice=price || '-' ;
            var _gsPos=pos || '-';
            _gsTracker.track('/targetpage/shoucang/'+_gsGoods+'/'+_gsNumber+'/'+_gsSize+'/'+_gsPrice+'/'+_gsPos); //然后可以通过页面完整路径，原生URL和网站目录层次进行查看
        }
    }
